package guida.ccf.gzuexaminesystem.config;

import guida.ccf.gzuexaminesystem.filter.JwtAuthenticationTokenFilter;
//import guida.ccf.gzuexaminesystem.security.AdminDetailsServiceImpl;
import guida.ccf.gzuexaminesystem.security.AdminDetailsServiceImpl;
import guida.ccf.gzuexaminesystem.security.StudentInfoDetailsServiceImpl;
import guida.ccf.gzuexaminesystem.security.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 *  配置 Spring Security 密码加密方式
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启权限控制功能
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthenticationTokenFilter tokenFilter;

    @Autowired
    private AccessDeniedHandler accessDeniedHandler;

    @Autowired
    private AuthenticationEntryPoint authenticationEntryPoint;

    @Autowired
    private UserDetailsServiceImpl userDetailsService;


    /**
     * @return 密码加密方式
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * AuthenticationManager 用户用户验证
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * 通过 userDetailsService 指定具体的 DetailsService.
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    @Override
    public void configure(WebSecurity web) {

        //放行静态资源
        web.ignoring().antMatchers(
                "/css/**",
                "/js/**",
                "/swagger-ui/**",
                "/swagger-ui.html",
                "/swagger-resources/**",
                "/images/**",
                "/webjars/**",
                "/v2/api-docs",
                "/configuration/ui",
                "/configuration/security",
                "/doc.html"
        );
    }

    /**
     *  放行接口
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        /*
            anonymous() 匿名访问.

            permitAll(): 允许所有用户访问，不需要进行身份验证。
            例如：.antMatchers(“/public”).permitAll()

            hasRole(): 要求用户具有特定的角色才能访问。
            例如：.antMatchers(“/admin”).hasRole(“ADMIN”)

            hasAnyRole(): 要求用户具有给定角色之一才能访问。
            例如：.antMatchers(“/admin”).hasAnyRole(“ADMIN”, “MANAGER”)

            hasAuthority(): 要求用户具有特定权限才能访问。
            例如：.antMatchers(“/admin”).hasAuthority(“ROLE_ADMIN”)

            hasAnyAuthority(): 要求用户具有给定权限之一才能访问。
            例如：.antMatchers(“/admin”).hasAnyAuthority(“ROLE_ADMIN”, “ROLE_MANAGER”)

            authenticated(): 要求用户在已经进行身份验证的情况下才能访问。
            例如：.antMatchers(“/user”).authenticated()
         */
        http
                // 关闭csrf, 防止csrf攻击.
                .csrf().disable()
                // 不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 对于登录接口 允许匿名访问
                .antMatchers(
                        "/admin/login",
                        "/studentInfo/login",
                        "/test/image",
                        "/studentInfo/getFile"
                )
                .anonymous()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated();

        /*
         * 配置 token 拦截器
         */
        http.addFilterAfter(tokenFilter, UsernamePasswordAuthenticationFilter.class);

        /*
         * 配置异常处理器
         */
        http
                // 认证异常
                .exceptionHandling().accessDeniedHandler(accessDeniedHandler)
                .and()
                // 授权异常
                .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);

        /*
         * Spring Security 设置跨域
         */
        http.cors();
    }
}
